using System;
using System.Collections;
using System.Web.UI;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// used to edit the protocol information(Title ,Version) 
    /// </summary>
    public partial class EditProtocolInfo : BasePage
    {
        #region Instance Vars.

        private ICachePolicy cachePolicy;
        private ProtocolProcess process;
        private Protocol protocol;
        private int protocolId;
        private int protocolProcessId;

        #endregion

        #region private properties

        /// <summary>
        /// Gets the protocol .If it's not already in the cache, it loads it up based on the protocolId passed to the page, and caches the object
        /// </summary>
        private Protocol Protocol
        {
            get
            {
                Hashtable incomingPageHash =
                    cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                Protocol currProtocol = null;
                if (incomingPageHash != null)
                {
                    protocolId = Convert.ToInt32(incomingPageHash[Keys.ProtocolIdKey]);
                    string cacheKey = Protocol.ProtocolKey;
                    currProtocol = cachePolicy.GetCachedObject(cacheKey) as Protocol;
                    if ((currProtocol == null) || (protocolId != currProtocol.Id))
                    {
                        if (protocolId != 0)
                        {
                            currProtocol = new Protocol(cachePolicy);
                            currProtocol.Load(DataAccess.GetConnectionString(), protocolId);
                            cachePolicy.Cache(cacheKey, protocol);
                        }
                        else
                        {
                            currProtocol = null;
                        }
                    }
                }
                return currProtocol;
            }
        }

        /// <summary>
        /// Gets the protocol process . If it's not already
        /// in the cache, it loads it up based on the protocolProcessId passed to the page, and caches the 
        /// object
        /// </summary>
        private ProtocolProcess ProtocolProcess
        {
            get
            {
                Hashtable incomingPageHash =
                    cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingPageHash != null)
                {
                    protocolProcessId = Convert.ToInt32(incomingPageHash[Keys.ProtocolProcessIdKey]);
                    process = cachePolicy.GetCachedObject(ProtocolProcess.ProtocolProcessKey)
                        as ProtocolProcess;

                    if ((process == null) || (protocolProcessId != process.Id))
                    {
                        if (protocolProcessId != 0)
                        {
                            process = ProtocolProcess.GetProtocolProcess(
                                DataAccess.GetConnectionString(), protocolProcessId, cachePolicy, null);
                            cachePolicy.Cache(ProtocolProcess.ProtocolProcessKey, process);
                        }
                        else
                        {
                            process = null;
                        }
                    }
                }
                return process;
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Loads the page according 
        /// </summary>
        /// <param name="sender">Originator of the event</param>
        /// <param name="e">event arguments of the originator</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    protocol = Protocol;
                    protocolTitle.Text = protocol.Title.Trim();
                    protocolVersion.Text = protocol.Version.Trim();
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = ex.Message;
            }
            finally
            {
                // set the header's protocol details.
                protocol = Protocol;
                protocolDetailHeader.ProtocolID = protocol.Id;
                if (Protocol.ModuleType == Constants.ModuleType.Animals)
                {
                    animalsSubModNavigation.Protocol = protocol;
                    animalsSubModNavigation.ProtocolProcess = ProtocolProcess;
                    versionLabel.Visible = false;
                    protocolVersion.Visible = false;
                    animalsSubModNavigation.Visible = true;
                }
                else
                {
                    humansSubModNavigation.ProtocolProcess = ProtocolProcess;
                    humansSubModNavigation.Protocol = protocol;
                    humansSubModNavigation.Visible = true;
                }
            }
        }

        /// <summary>
        /// Eventhandler for the save button click
        /// </summary>
        /// <param name="sender">originator(Save Button)</param>
        /// <param name="e">EventArgs of the Originator</param>
        private void OnSaveProtocolClick(object sender, ImageClickEventArgs e)
        {
            try
            {
                if (protocolTitle.Text.Trim() == string.Empty)
                {
                    annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                    annunciator.Message = "Full title of the study is empty.";
                    return;
                }
                Protocol protocol = Protocol;
                // set the Protocol strings from teh fields on the screen.
                protocol.Title = protocolTitle.Text.Trim();
                if (protocol.ModuleType != Constants.ModuleType.Animals)
                {
                    protocol.Version = protocolVersion.Text.Trim();
                }
                protocol.Save(DataAccess.GetConnectionString());
                cachePolicy.Cache(protocol.CacheKey(), protocol);
                RedirectPage();
            }
            catch (Exception ex)
            {
                annunciator.Message = ex.Message;
            }
        }

        /// <summary>
        /// Event Handler for the cancel button click
        /// </summary>
        /// <param name="sender">originator(Cancel Button)</param>
        /// <param name="e">EventArgs of the Originator</param>
        private void OnCancelProtocolClick(object sender, ImageClickEventArgs e)
        {
            RedirectPage();
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Redirects the page back to the ProtocolProcessOverview page
        /// </summary>
        private void RedirectPage()
        {
            Hashtable incomingPageHash =
                cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            object pageReferrer = incomingPageHash[Keys.PageReferrerKey];
            object fromClone = incomingPageHash["IsClone"];
            if (fromClone != null && (bool) fromClone)
            {
                Response.Redirect(Settings.GetKeyValue("SubNavigation.Humans.WorkInProgressURL", ""));
            }
            if (pageReferrer != null && pageReferrer.ToString() == "ProtocolDetails")
            {
                Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolDetailsURL", ""), false);
            }
            else
            {
                Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolProcessOverviewURL", ""), false);
            }
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.saveProtocol.Click += new ImageClickEventHandler(OnSaveProtocolClick);
            this.cancelProtocol.Click += new ImageClickEventHandler(OnCancelProtocolClick);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion
    }
}